<template>
	<div class="pdfContainer">
		<div class="app-header">
			<template v-if="isLoading"> Loading... </template>

			<template v-else>
				<span v-if="showAllPages"> {{ pageCount }} page(s) </span>

				<span v-else>
					<button :disabled="!!page && page <= 1" @click="!!page && page--">❮</button>

					{{ page }} / {{ pageCount }}

					<button :disabled="!!page && !!pageCount && page >= pageCount" @click="!!page && page++">❯</button>
				</span>

				<label class="right">
					<input v-model="showAllPages" type="checkbox" />

					Show all pages
				</label>

				<button @click="downLoad">下载</button>
			</template>
		</div>

		<div class="app-content">
			<vue-pdf-embed
				ref="pdfRef"
				:source="props.pdfUrl"
				:page="page || undefined"
				@password-requested="handlePasswordRequest"
				@loaded="handleDocumentLoad"
				@rendered="handleDocumentRender"
			/>
		</div>
	</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
import VuePdfEmbed from 'vue-pdf-embed';
import 'vue-pdf-embed/dist/style/index.css';
// optional styles
import 'vue-pdf-embed/dist/style/annotationLayer.css';
import 'vue-pdf-embed/dist/style/textLayer.css';

const props = defineProps({
	pdfUrl: {
		type: String,
	},
});
const isLoading = ref(true);
const showAllPages = ref(true);
const page = ref<number | null>(null);
const pageCount = ref<number | null>(null);

watch(showAllPages, () => {
	page.value = showAllPages.value ? null : 1;
});

type IDocumentLoad = (object: { numPages: number }) => void;
const handleDocumentLoad: IDocumentLoad = ({ numPages }): void => {
	pageCount.value = numPages;
};
const handleDocumentRender = () => {
	isLoading.value = false;
};

const handlePasswordRequest = ({ callback, isWrongPassword }: { callback: any; isWrongPassword: any }) => {
	callback(prompt(isWrongPassword ? 'Enter password again' : 'Enter password'));
};

const pdfRef = ref<any>();
const downLoad = () => {
	pdfRef.value.download();
};
</script>

<style lang="scss" scoped>
.pdfContainer {
	width: 100%;
	height: 80vh;
	background-color: #fff;
	position: relative;
	.app-header {
		width: 100%;
		height: 50px;
		background-color: #ec7373;
	}
	.app-content {
		width: 100%;
		height: 80vh;
		overflow-y: auto;
		overflow-x: hidden;
	}
}
</style>
